var model = avalon.define({
    $id: "apply",
    businessType: "", // 业务类型
    token: "",
    grid_url: "",
    departname: "",
    username: "",
    uploadtype: "", // 上传文件的业务类型
    sheet: {},
    applys: [],
    applyName: "", //
    applyHtml: "",
    particsItem: "",
    productItem: "",
    bill: "", //
    b_date: "",
    e_date: "",
    pagesize: 10,
    currentPage: 0,
    query: {
        keyword: "",
        start_date: "",
        end_date: "",
        apply_type: "",
    },
    timestamp: "",
    start_date: "",
    end_date: "",
    partics: [], //品名库信息
    errorIdCards: [],
    idCards: [],
    dictItems: [], //数据字典

    usernameError: "", //错误信息
    downApplyId: "", //税款清单，海关清单下载Id
    exportDialog: "", //导出清单对话框

    // dicts:["一般贸易","保税业务","快件业务"],
    // [{ value: "FOB", text: "一般贸易" }, { value: "EXP-B", text: "快件业务B类" }, { value: "EXP-C", text: "快件业务C类" }, { value: "CEB", text: "跨境业务" }], //业务类型 ,先去掉：,{ value: "C", text: "保税业务" }
    typeDicts: [], //业务类型 ,先去掉：,{ value: "C", text: "保税业务" }
    modelDicts: [{
        value: "5",
        text: "航空运输"
    }, {
        value: "2",
        text: "水路运输"
    }], //运输方式
    firstSelected: "快件业务",
    apply: {
        applyType: "", //业务类型
        departId: "", //组织编号
        memo: "", //描述
        applyName: "", //业务名称
        shipType: "", //运输方式
        imSign: "I", //进出境标志
        isCross: "0", //是否跨境
        mBillNo: "", //提运单号
        port: "", //进出口岸代码
        byName: "", //创建人
        id: ""
    },
    applyId: "", //业务号

    sheets: [],
    sheetName: "",
    type: "", //上传类型

    dpeartParentName: "", //上级组织结构名称
    //departType: 2, //验证是什么类型
    departLevelValue: [{
        value: "0",
        text: "0"
    }, {
        value: "1",
        text: "1"
    }, {
        value: "2",
        text: "2"
    }], //级别
    depart: {
        deptLevel_NR: "", //级别 departLevel
        parentID: "", //上级组织结构 departNo
        departName: "", //组织结构名称
        memo_TX: "", //组织机构简称 memo
        tagName: "", //索引码
        departCD: "", //企业代码
        prefix: "", //面单前缀
        departType: "2" //企业类型
    },
    products: {
        gname: "",
        hscode: "",
        unit1: "",
        postal: "",
        unit2: "",
        customs: "",
        typeCode: "KJ_B",
    },

    onInit: function() {
        avalon.log('ok');
    },
    init: function() {
        model.loadGrid();
        model.addEvent();
        validate();
    },
    loadGrid: function() {},
    addEvent: function() {
        var t = this;
        $(".grid-wrap").on("click", ".fa-eye", function(t) {
            var e = $(this).parent().data("id");
            model.viewdproduct(e);
        });
        //修改
        $(".grid-wrap").on("click", ".fa-edit", function(e) {
            var id = $(this).parent().data("count");
            // var id = $(this).parent().data("id");

            $.ajax({
                url: "/api/apply/getinfo?id=" + id,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("X-AuthToken", model.token);
                },
                success: function(data) {
                    model.edit(data.data);
                },
                error: function(data) {
                    dialog({
                        title: "错误",
                        content: "系统出现异常",
                        okValue: "确定",
                        ok: function() {}
                    })
                }
            })

            // model.edit($("#grid").getRowData(id));
        });
        // 删除
        $(".grid-wrap").on("click", ".fa-trash-o", function(t) {
            var ei = [];
            var e = $(this).parent().data("id");
            ei.push(e);
            model.del(ei);
        });

        //上传文件
        $(".grid-wrap").on("click", ".uploadfile", function(t) {
            // 获取选中行id
            var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                applyId = $("#grid").jqGrid("getRowData", id).applyId;
            model.id = id;
            model.applyId = applyId;
            model.uploadtype = this.name;
            model.openfiledialog();
        });

        //下载文件
        $(".grid-wrap").on("click", ".downloadfile", function(t) {
            var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                applyId = $("#grid").jqGrid("getRowData", id).applyId,
                aTag = $(this);

            downloadFile(aTag, applyId);
            // return false;
        });

        $(".grid-wrap").on("click", ".identification", function(t) {
            var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                applyId = $("#grid").jqGrid("getRowData", id).applyId;
            dialog({
                id: "identify001",
                content: "正在获取数据，请稍候..."
            }).showModal()
            $.ajax({
                url: "/api/inventory/recheckup?applyId=" + applyId,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("X-AuthToken", model.token);
                },
                success: function(data) {
                    dialog.get("identify001").close().remove();
                    model.timestamp = "";
                    idCardInfoEdit(data.data, applyId);
                },
                error: function(data) {
                    dialog.get("identify001").close().remove();

                }
            })
            // return false;
        });

        $(".grid-wrap").on("click", ".downloadident", function(t) {
            var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                applyId = $("#grid").jqGrid("getRowData", id).applyId;
            downloadIdentInfo(applyId, "identification");
            // return false;
        });

        //生成面单
        $(".grid-wrap").on("click", ".generate", function(t) {
            // 获取选中行id
            var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                applyId = $("#grid").jqGrid("getRowData", id).applyId;
            $.ajax({
                url: "/api/waybills/generate",
                data: {
                    "applyId": applyId,
                    "byName": model.username
                },
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("X-AuthToken", model.token);
                },
                success: function(data) {
                    model.reloadData();
                },
                error: function() {
                    parent.artDialog()
                        .title("错误")
                        .content("系统异常")
                        .button([{
                            value: '确定',
                            autofocus: true,
                            callback: function() {}
                        }])
                }
            })
        });

        // 品名匹配
        $(".grid-wrap").on("click", ".matching", function() {
            // 获取id
            var id = $("#grid").jqGrid('getGridParam', 'selrow');
            // 获取业务单号
            var applyId = $("#grid").jqGrid("getRowData", id).applyId;
            // 获取业务类型
            var type = $("#grid").jqGrid("getRowData", id).applyType;
            model.matching(applyId, type);
        });
        $("#search").click(function(e) {
            e.preventDefault();
            if (model.start_date != "") {
                model.query.start_date = model.start_date + " 00:00:00";
            }
            if (model.end_date != "") {
                model.query.end_date = model.end_date + " 23:59:59";
            }
            model.reloadData();
        });
        $("#refresh").click(function(e) {
            e.preventDefault();
            model.reset();
        });
        // 新增
        $("#add").click(function(t) {
            model.edit(-1);
        });
        // 新增组织机构
        $("#addDepart").click(function(t) {
            model.addDepart(-1);
        });
        // 批量删除
        $("#btn-batchDel").click(function(t) {
            var ids = $("#grid").jqGrid("getGridParam", "selarrrow");
            var applyIds = [];
            $(ids).each(function(index, id) {
                var applyId = $("#grid").jqGrid("getRowData", id).applyId;
                applyIds.push(applyId);
            })
            model.del(applyIds);
        });

    },

    reset: function() {
        model.fastQryText = "快速查询";
        model.start_date = "";
        model.end_date = "";
        model.query = {
            keyword: "",
            start_date: "",
            end_date: "",
            apply_type: model.apply_type,
        };
        model.reloadData();
    },
    reloadData: function() {
        $("#grid").jqGrid("setGridParam", {
            url: model.grid_url,
            datatype: "json",
            mtype: 'POST',
            postData: model.query.$model,
            page: 1
        }).trigger("reloadGrid");
    },
    openfiledialog: function() { //打开上传对话框
        const fileInput = document.querySelector('input[type="file"]');
        fileInput.addEventListener('change', function() {
            this.value = ''; //打开对话框后清除上次的记录
        })
        $('#upload-file-input').click();
    },
    uploadfile: function() { //执行上传
        uploadFile();
    },
    matching: function(applyId, type) {
        matching(applyId, type);
    },
    closeExportDialog: function() {
        model.exportDialog.close();
    },
    exportExcel: function(applyId) { //执行导入
        model.downApplyId = applyId;
        model.exportDialog = dialog({
            title: '导出Excel',
            content: $('#exportExcelSH'),
            height: '100',
            id: 'EF893L14'
        }).showModal();
    },
    edit: function(el) {
        editApply(el);
    },
    addDepart: function(argument) {
        saveDepart(argument);
    },
    del: function(applyIds) {
        deleteApply(applyIds);
    },
    test: function() {
        console.log(model.dictItems);
    }

});
